layui.use(['table', 'admin', 'ax', 'func','upload','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var upload = layui.upload;
    var form = layui.form;

    /**
     * 双证管理管理
     */
    var BtySzgl = {
        tableId: "btySzglTable"
    };

    /**
     * 检索营运经理
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btySzgl/yyjlList");
    var languageResult = languageAjax.start();
    $.each(languageResult.data, function( index, val ) {
        $("#yyjl").append("<option value='"+val.yyjl+"'>"+val.yyjl+"</option>");
    } );
    form.render('select');


    /**
     * 检索区域
     */
    var qyAjax = new $ax("/area/getAreaByType");
    qyAjax.set("type", 2);
    var qyResult = qyAjax.start();
    $.each(qyResult, function (index, data) {
        $("#firstArea").append("<option value='" + data.id + "'>" + data.simpleName + "</option>");
    });
    form.render('select');
    form.on('select(firstArea)', function (data) {
        var pid = data.value;
        if (pid == "") {
            $("#secondArea").html("");
            $("#secondArea").append("<option value=''>全部二级区域</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/area/getAreaByPid");
            qyAjax.set("pid", pid);
            var qyResult = qyAjax.start();
            $("#secondArea").html("");
            $("#secondArea").append("<option value=''>全部二级区域</option>");
            $.each(qyResult, function (index, data) {
                $("#secondArea").append("<option value='" + data.id + "'>" + data.simpleName + "</option>");
            });
            form.render('select');
        }
    });


    /**
     * 初始化表格的列
     */
    BtySzgl.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: ''},
            {field: 'firstArea', title: '一级区域'},
            {field: 'secondArea', title: '二级区域'},
            {field: 'tiancai', title: '天财店名',width:180},
            {field: 'yaoma', title: '妖码'},
            {field: 'dm', title: '工程店名',width:180},
            {field: 'gcAddress', title: '工程地址',width:180},
            {field: 'yyjl', title: '营运经理'},
            {field: 'yyzzfr', title: '法人姓名'},
            {field: 'frCard', title: '法人身份证', templet: function (d) {
                    if (d.frCard === undefined || d.frCard === "") {
                        return "<p>暂无</p>";
                    } else {
                        if (d.frCard.indexOf(",") != -1){
                            var a = d.frCard.split(",")[0];
                            var b = d.frCard.split(",")[1];
                            return "<img src='" + a + "' style='max-width: 50%;' onclick='imgViewer(this)' class='img'>" +
                                "<img src='" + b + "' style='max-width: 50%;' onclick='imgViewer(this)' class='img'>";
                        }else {
                            return "<img src='" + d.frCard + "' style='max-width: 100%;' onclick='imgViewer(this)' class='img'>";
                        }
                    }
                }},
            {field: 'mt', title: '美团店名',width:180},
            {field: 'elm', title: '饿了么店名',width:180},
            {field: 'spjyxkz', title: '食品经营许可证',templet: function (d) {
                    if (d.spjyxkz === undefined || d.spjyxkz === "") {
                        return "<p>暂无</p>";
                    } else {
                        return "<img src='" + d.spjyxkz + "' style='max-width: 100%;' onclick='imgViewer(this)' class='img'>";
                    }
                }},
            {field: 'spjyxkzrq', title: '食品经营许可证截止日期',width:100},
            {field: 'yyzz', title: '营业执照', templet: function (d) {
                    if (d.yyzz === undefined || d.yyzz === "") {
                        return "<p>暂无</p>";
                    } else {
                        return "<img src='" + d.yyzz + "' style='max-width: 100%;' onclick='imgViewer(this)' class='img'>";
                    }
                }},
            {field: 'yyzzmc', title: '营业执照名称',width:180},
            {field: 'shxydm', title: '统一社会信用代码',width:180},
            {field: 'yyzzdz', title: '营业执照地址',width:180},

            // {field: 'sta', title: '状态：0->图片为工程同步,1->图片为手动添加'},
            {align: 'center', toolbar: '#tableBar', title: '操作',fixed: 'right'}
        ]];
    };


    var tempView = null
    imgViewer = function (img) {
        let _tr = $(img).parents('tr');
        let index = $(_tr).index();
        tempView = $('.layui-table-main tbody tr[data-index= ' + index + ']')
        tempView.viewer()
        return
    };


    // 重置按钮事件
    $('#btnReset').click(function () {
        $('input').val('');
        $("#name").val('');
        $("#yaoma").val('');
        $("#yyjl").val('');
        $("#firstArea").val('');
        $("#secondArea").val('');
        form.render();
    });

    /**
     * 点击查询按钮
     */
    BtySzgl.search = function () {
        var queryData = {};

        queryData['name'] = $('#name').val();
        queryData['yaoma'] = $('#yaoma').val();
        queryData['yyjl'] = $('#yyjl').val();
        var firstArea = $("#firstArea").find("option:selected").text() == '全部一级区域' ? '' : $("#firstArea").find("option:selected").text();
        var secondArea = $("#secondArea").find("option:selected").text() == '全部二级区域' ? '' : $("#secondArea").find("option:selected").text();
        queryData['firstArea'] = firstArea;
        queryData['secondArea'] = secondArea;

        table.reload(BtySzgl.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加对话框
     */
    BtySzgl.openAddDlg = function () {
        func.open({
            title: '添加双证管理',
            content: Feng.ctxPath + '/btySzgl/add',
            tableId: BtySzgl.tableId
        });
    };

     /**
      * 点击编辑
      *
      * @param data 点击按钮时候的行数据
      */
      BtySzgl.openEditDlg = function (data) {
          func.open({
              title: data.tiancai + '(' + data.yaoma + ')',
              content: Feng.ctxPath + '/btySzgl/edit?id=' + data.id,
              tableId: BtySzgl.tableId
          });
      };


    /**
     * 导出双证按钮
     */
    var _delay = false;
    BtySzgl.exportPic = function () {
        var checkRows = table.checkStatus(BtySzgl.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的店面");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                if(_delay) {
                    return;
                };
                _delay = true;
                setTimeout(() =>{
                    _delay = false
                },2000);
                var ajax = new $ax(Feng.ctxPath + "/btySzgl/btnDown", function () {
                    $("#ways")[0].click();
                    Feng.success("下载成功!");
                    table.reload(BtySzgl.tableId);
                }, function (result) {
                    Feng.error("下载失败!" + result.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.start();
            };
            Feng.confirm("是否批量下载?", operation);
        }
    };

    /**
     * 导出excel按钮
     */
    BtySzgl.exportExcel = function () {
        //获取导出的数据
        // var ajax = new $ax(Feng.ctxPath + "/btySzgl/expList");
        var name = $("#name").val();
        var yaoma = $("#yaoma").val();
        var yyjl = $("#yyjl  option:selected").val();
        var firstArea = $("#firstArea").find("option:selected").text() == '全部一级区域' ? '' : $("#firstArea").find("option:selected").text();
        var secondArea = $("#secondArea").find("option:selected").text() == '全部二级区域' ? '' : $("#secondArea").find("option:selected").text();
        // ajax.set("name", name);
        // ajax.set("yaoma", yaoma);
        // ajax.set("yyjl", yyjl);
        // var result = ajax.start();
        // table.exportFile(tableResult.config.id, result, 'xls');

        //获取导出Excel的数据
        var url = Feng.ctxPath + "/btySzgl/expList?name=" + name + "&yaoma=" + yaoma + "&yyjl=" + yyjl + "&firstArea=" + firstArea + "&secondArea=" + secondArea;
        location.href = url;
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    BtySzgl.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btySzgl/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(BtySzgl.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + BtySzgl.tableId,
        url: Feng.ctxPath + '/btySzgl/list',
        page: true,
        height: "full-110",
        cellMinWidth: 100,
        limit: 20,
        cols: BtySzgl.initColumn()
    });

    /**
     * 导入Excel
     */
    var loadIndex;
    upload.render({
        elem: '#btnExcel'
        , url: '/btySzgl/import'
        , accept: "file"
        , async: false
        , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
        ,before: function(obj){//参数
            loadIndex = layer.load('正在导入...',2, { shade: [0.15, '#ccc'] });
        }
        , done: function (res) {
            if (res == true) {
                layer.msg('导入成功！', {icon: 1, time: 2000, shade: 0.2});
                layer.close(loadIndex);
                table.reload(BtySzgl.tableId);
            }else {
                layer.msg('导入失败！', {icon: 1, time: 2000, shade: 0.2});
                layer.close(loadIndex);
            }
        },
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BtySzgl.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

    BtySzgl.openAddDlg();

    });

    // 导出双证
    $('#btnExpPic').click(function () {
        BtySzgl.exportPic();
    });

    // 导出excel
    $('#btnExp').click(function () {
        BtySzgl.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + BtySzgl.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            BtySzgl.openEditDlg(data);
        } else if (layEvent === 'delete') {
            BtySzgl.onDeleteItem(data);
        }
    });
});
